<template>
  <div class="main">
    <div class="part single">
      <div class="p-title">
        <div class="title">管理概览</div>
        <div class="search">
          <myDestSelect @destChange="destChange" ref="destSelectRef" />
          <!-- <el-date-picker
            v-model="dateValue"
            type="daterange"
            range-separator="To"
            start-placeholder="Start date"
            end-placeholder="End date"
          /> -->
        </div>
      </div>
      <div class="p-cont">
        <div class="drug">
          <!-- <div class="title">
            管理居民总数 (人）
            <span>17126</span>
          </div> -->
          <div class="user-panel">
            <div class="up-item">
              <div class="up-des">
                <span>管理居民总数 (人）</span>
                <MyToolTip
                  content="指标定义：截止到筛选日期的一个自然年内，接受平台健康管理服务的居民用户绝对人数。"
                />
              </div>
              <div class="up-num">
                {{ formatNum(memberTotalNum) }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div class="up-item">
              <div class="up-des">
                <span>慢性病改善 (人次)</span>
                <MyToolTip
                  content="指标定义：截止到筛选日期的一个自然年内，通过监测用户的健康数据，确认其健康水平提高、慢性病病情得到改善提升的人次总数"
                />
              </div>
              <div class="up-num">
                {{ formatNum(chronicDiseaseBetterNum) }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="red"
                  />
                  <span class="red">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div class="up-item">
              <div class="up-des">
                <span>用药改善（人次）</span>
                <MyToolTip
                  content="指标定义：截止到筛选日期的一个自然年内，通过监测用户的用户数据，确认其用药过程中的安全性、依从性和用药效果得到改善提升的人次总数"
                />
              </div>
              <div class="up-num">{{ formatNum(useDrugBetterNum) }}</div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
            <div class="up-item">
              <div class="up-des">
                <span>会员满意度</span>
                <MyToolTip
                  content="指标定义：截止到筛选日期的一个自然年内，参与平台用户满意度调查并认为服务让人“满意”和“基本满意”的人次百分比"
                />
              </div>
              <div class="up-num">
                {{ (memOkNum && memOkNum * 100 + "%") || "0" }}
              </div>
              <!-- <div class="up-inc">
                <div class="up-inc-left">
                  <span>环比</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
                <div class="up-inc-right">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div> -->
            </div>
          </div>
        </div>
        <div class="trend">
          <!-- <div class="title">趋势分析(人)</div> -->
          <div class="trend-content">
            <div class="tc-left">
              <div class="tc-btn">
                <el-button type="primary">导出详情数据</el-button>
                <el-button-group class="ml-4">
                  <el-button plain>按日</el-button>
                  <el-button plain>按周</el-button>
                  <el-button plain>按月</el-button>
                </el-button-group>
              </div>

              <div class="tc-line" ref="trendLineRef" />
            </div>
            <div class="tc-right">
              <div class="tc-r-item">
                <div class="tc-r-title">
                  <span> 管理金额规模 (元)</span>
                  <MyToolTip content="" />
                </div>
                <div class="tc-r-num">872,192,722</div>
                <div class="tc-r-inc">
                  <span>自从上周以来</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="green"
                  />
                  <span class="green">12.5%</span>
                </div>
              </div>
              <div class="tc-r-item">
                <div class="tc-r-title">
                  <span> 避免再住院金额 (元)</span>
                  <MyToolTip content="" />
                </div>
                <div class="tc-r-num">
                  {{ formatNum(indexValue[1] && indexValue[1].value) }}
                </div>
                <div class="tc-r-inc">
                  <span>自从上周以来</span>
                  <IconifyIconOnline
                    icon="material-symbols:arrow-circle-down-outline-rounded"
                    width="20px"
                    height="20px"
                    class="red"
                  />
                  <span class="red">12.5%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="part">
      <div class="section">
        <div class="title">
          用户画像
          <!-- <span>17126</span> -->
        </div>
        <div class="user-panel">
          <div class="up-item">
            <div class="up-des">
              <span>近12个月总医疗支出（元）</span>
              <MyToolTip
                content="指标定义：截止到筛选日期的一个自然年内，基于用户提供的最近一年的健康管理数据统计的全医疗花费之和，包括药费、检查费、住院费和其他类型的医疗服务费。"
              />
            </div>
            <div class="up-num">
              {{ formatNum(indexValue[5] && indexValue[5].value) }}
            </div>
            <!-- <div class="up-inc">
              <div class="up-inc-left">
                <span>环比</span>
                <IconifyIconOnline
                  icon="material-symbols:arrow-circle-down-outline-rounded"
                  width="20px"
                  height="20px"
                  class="green"
                />
                <span class="green">12.5%</span>
              </div>
              <div class="up-inc-right">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div> -->
          </div>
          <div class="up-item">
            <div class="up-des">
              <span>人均医疗支出 (元)</span>
              <MyToolTip
                content="指标定义：截止到筛选日期的一个自然年内，有医疗支出的用户平均每人的医疗花费"
              />
            </div>
            <div class="up-num">
              {{ formatNum(indexValue[6] && indexValue[6].value) }}
            </div>
            <!-- <div class="up-inc">
              <div class="up-inc-left">
                <span>环比</span>
                <IconifyIconOnline
                  icon="material-symbols:arrow-circle-down-outline-rounded"
                  width="20px"
                  height="20px"
                  class="red"
                />
                <span class="red">12.5%</span>
              </div>
              <div class="up-inc-right">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div> -->
          </div>
          <div class="up-item hidden" />
          <div class="up-item hidden" />
        </div>
        <div class="chart">
          <div class="chart-left chart-item">
            <div class="ch-btns">
              <div class="chart-title">
                <span>健康风险比例</span>
                <MyToolTip
                  content="指标定义：截止到筛选日期的一个自然年内，通过人工智能引擎分析出的个人综合健康风险的分级，并按照高中低的方式予以分级。"
                />
              </div>
              <el-button
                plain
                :type="
                  userDataHealthRiskRatioType === 'num' ? 'primary' : 'default'
                "
                @click="clickGetHealthIndexHospitalRiskData"
                >按人数</el-button
              >
              <el-button
                plain
                :type="
                  userDataHealthRiskRatioType === 'medical'
                    ? 'primary'
                    : 'default'
                "
                @click="clickGetHealthIndexHospitalRiskData"
                >按医疗支出</el-button
              >
            </div>
            <div class="ch-chart" ref="userChartRef" />
          </div>
          <div class="chart-right chart-item">
            <div class="ch-btns">
              <div class="chart-title">
                <span>会员疾病分布</span>
                <MyToolTip
                  content="指标定义：截止到筛选日期的一个自然年内，按照会员所患的疾病分类汇总分布情况"
                />
              </div>
              <el-button
                plain
                :type="
                  userDataDiseaseRatioType === 'num' ? 'primary' : 'default'
                "
                @click="changeDiseaseRatioType"
                >按人数</el-button
              >
              <el-button
                plain
                :type="
                  userDataDiseaseRatioType === 'medical' ? 'primary' : 'default'
                "
                @click="changeDiseaseRatioType"
                >按医疗支出</el-button
              >
            </div>
            <div class="ch-list">
              <el-table :data="userDataDiseaseRatioData" style="width: 100%">
                <el-table-column label="排名" width="180">
                  <template #default="scope">
                    <span class="ch-t-index" style="margin-left: 10px">{{
                      scope.row.index
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="疾病" width="220" />
                <el-table-column prop="value" label="分布情况" width="300">
                  <template #default="scope">
                    <div class="ch-t-cont">
                      <div class="ch-t-bar">
                        <div
                          class="ch-t-bar-inner"
                          :style="{ width: scope.row.width + 'px' }"
                        />
                      </div>
                      <div class="ch-t-num">
                        {{ scope.row.value + "%" }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="part">
      <div class="section">
        <div class="title">
          慢病管理效果
          <!-- <span>17126</span> -->
        </div>
        <div class="user-panel">
          <div class="up-item">
            <div class="up-des">
              <span>避免慢病严重并发症住院（人次）</span>
              <MyToolTip
                content="指标定义：截止到筛选日期的一个自然年内，基于用户慢性病改善和用药的改善，因此一定程度上会避免一些因慢性病导致的严重并发症发生，人工智能引擎则根据大量历史临床数据结合改善情况预估出相应减少的人次数量"
              />
            </div>
            <div class="up-num">
              {{ formatNum(indexValue[0] && indexValue[0].value) }}
            </div>
            <!-- <div class="up-inc">
              <div class="up-inc-left">
                <span>环比</span>
                <IconifyIconOnline
                  icon="material-symbols:arrow-circle-down-outline-rounded"
                  width="20px"
                  height="20px"
                  class="green"
                />
                <span class="green">12.5%</span>
              </div>
              <div class="up-inc-right">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div> -->
          </div>
          <div class="up-item">
            <div class="up-des">
              <span>避免慢病严重并发症住院费用 (元)</span>
              <MyToolTip
                content="指标定义：截止到筛选日期的一个自然年内，基于避免慢性严重并发症的人次结合全国人均住院医疗花费预估避免掉的住院费用"
              />
            </div>
            <div class="up-num">
              {{ formatNum(indexValue[1] && indexValue[1].value) }}
            </div>
            <!-- <div class="up-inc">
              <div class="up-inc-left">
                <span>环比</span>
                <IconifyIconOnline
                  icon="material-symbols:arrow-circle-down-outline-rounded"
                  width="20px"
                  height="20px"
                  class="red"
                />
                <span class="red">12.5%</span>
              </div>
              <div class="up-inc-right">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div> -->
          </div>
          <div class="up-item hidden" />
          <div class="up-item hidden" />
        </div>
        <div class="chart">
          <div class="chart-left chart-item chart-flex-col">
            <!-- <div class="ch-btns">
              <el-button plain>按人数</el-button>
              <el-button plain>按医疗支出</el-button>
            </div> -->
            <div class="ch-btns">
              <div class="chart-title">
                <span>达标率（与管理前比较）</span>
                <MyToolTip
                  content="指标定义：截止到筛选日期的一个自然年内，用户在进行健康管理前后，生化指标数据达标比例的对比"
                />
              </div>
              <div />
            </div>

            <!-- <div class="ch-chart" ref="userChartRef" /> -->
            <div class="ch-row">
              <div class="ch-col-label">血压</div>
              <div class="ch-col-pie ch-col-pie1" ref="slowDiseaseXyRef1" />
              <div class="ch-col-pie ch-col-pie2" ref="slowDiseaseXyRef2" />
            </div>
            <div class="ch-row">
              <div class="ch-col-label">血糖</div>
              <div class="ch-col-pie ch-col-pie1" ref="slowDiseaseXtRef1" />
              <div class="ch-col-pie ch-col-pie2" ref="slowDiseaseXtRef2" />
            </div>
            <div class="ch-row">
              <div class="ch-col-label">血脂</div>
              <div class="ch-col-pie ch-col-pie1" ref="slowDiseaseXzRef1" />
              <div class="ch-col-pie ch-col-pie2" ref="slowDiseaseXzRef2" />
            </div>
          </div>
          <div class="chart-right chart-item">
            <div class="ch-btns">
              <div class="chart-title">
                <span>避免住院情况</span>
                <MyToolTip
                  content="指标定义：截止到筛选日期的一个自然年内，根据引擎预估的避免出现的严重并发症发生的人次，按照并发症疾病的人次分布情况"
                />
              </div>
              <el-button
                plain
                :type="reHospitalRatioType === 'num' ? 'primary' : 'default'"
                @click="changeReHospitalType"
                >按人次</el-button
              >
              <el-button
                plain
                :type="
                  reHospitalRatioType === 'medical' ? 'primary' : 'default'
                "
                @click="changeReHospitalType"
                >按医疗支出</el-button
              >
            </div>
            <div class="ch-list">
              <div class="ch-list-title" />
              <el-table :data="reHospitalRatioData" style="width: 100%">
                <el-table-column prop="name" label="疾病" width="180" />
                <el-table-column prop="value" label="分布情况" width="300">
                  <template #default="scope">
                    <div class="ch-t-cont">
                      <div class="ch-t-bar">
                        <div
                          class="ch-t-bar-inner"
                          :style="{ width: scope.row.width + 'px' }"
                        />
                      </div>
                      <div class="ch-t-num">
                        {{ scope.row.value }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column />
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="part part2">
      <div class="section">
        <div class="title">
          重疾管理效果
          <!-- <span>17126</span> -->
        </div>
        <div class="user-panel">
          <div class="up-item">
            <div class="up-des">
              <span>重疾早发现（人）</span>
              <MyToolTip
                content="指标定义：截止到筛选日期的一个自然年内，通过重疾早筛服务发现的重疾形成期/早期病人的人数"
              />
            </div>
            <div class="up-num">
              {{ formatNum(indexValue[2] && indexValue[2].value) }}
            </div>
            <!-- <div class="up-inc">
              <div class="up-inc-left">
                <span>环比</span>
                <IconifyIconOnline
                  icon="material-symbols:arrow-circle-down-outline-rounded"
                  width="20px"
                  height="20px"
                  class="green"
                />
                <span class="green">12.5%</span>
              </div>
              <div class="up-inc-right">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div> -->
          </div>
          <div class="up-item">
            <div class="up-des">
              <span>节省医疗支出总金额 (元)</span>
              <MyToolTip
                content="指标定义：截止到筛选日期的一个自然年内，通过早筛及时发现的早期重疾的，因病情相对较轻，与中晚期重疾比较，治疗手段较多，治疗费用显著下降，因而节省的医疗费用支出的金额"
              />
            </div>
            <div class="up-num">
              {{ formatNum(indexValue[3] && indexValue[3].value) }}
            </div>
            <!-- <div class="up-inc">
              <div class="up-inc-left">
                <span>环比</span>
                <IconifyIconOnline
                  icon="material-symbols:arrow-circle-down-outline-rounded"
                  width="20px"
                  height="20px"
                  class="red"
                />
                <span class="red">12.5%</span>
              </div>
              <div class="up-inc-right">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div> -->
          </div>
        </div>
      </div>
      <div class="section">
        <div class="chart">
          <div class="chart-right chart-item">
            <div class="ch-btns">
              <div class="chart-title">
                <span>重疾管理效果</span>
                <MyToolTip
                  content="指标定义：截止到筛选日期，通过早筛及时发现的早期重疾用户按疾病的人数分布情况"
                />
              </div>
              <el-button
                plain
                :type="seriousIllnessType === 'num' ? 'primary' : 'default'"
                @click="changeSeriousIllnessType"
                >按人数</el-button
              >
              <el-button
                plain
                :type="seriousIllnessType === 'medical' ? 'primary' : 'default'"
                @click="changeSeriousIllnessType"
                >按医疗支出</el-button
              >
            </div>
            <div class="ch-list">
              <el-table :data="seriousIllnessData" style="width: 100%">
                <el-table-column prop="name" label="疾病" width="180" />
                <el-table-column prop="value" label="分布情况" width="300">
                  <template #default="scope">
                    <div class="ch-t-cont">
                      <div class="ch-t-bar">
                        <div
                          class="ch-t-bar-inner"
                          :style="{ width: scope.row.width + 'px' }"
                        />
                      </div>
                      <div class="ch-t-num">
                        {{ scope.row.value }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  onBeforeMount,
  onMounted,
  ref,
  Ref,
  onUnmounted,
  getCurrentInstance
} from "vue";
import { ArrowRight } from "@element-plus/icons-vue";
import { useECharts } from "@pureadmin/utils";
import * as echartsTypes from "echarts/types/dist/echarts";
import {
  getHealthIndexOverview,
  getHealthIndexHospitalRiskByNum,
  getHealthIndexHospitalRiskByMedical,
  getHealthIndexMemberRatioByNum,
  getHealthIndexMemberRatioByMedical,
  getMemberNum,
  getChronicDiseaseBetterNum,
  getUseDrugBetterNum,
  getMemOkNum,
  getXyRate,
  getXtRate,
  getXzRate,
  getReHospitalDataByNum,
  getReHospitalDataByMedical,
  type RiskDataType,
  getSeriousIllnessDataByNum,
  getSeriousIllnessDataByMedical
} from "@/api/health";
import { formatNum, lastWeeks } from "@/utils/tools";
import { reactive } from "vue";
import { globalDataStoreHook } from "@/store/modules/globalData";
import MyToolTip from "@/components/myToolTip.vue";
import myDestSelect, { destSelectType } from "@/components/myDestSelect.vue";

const destSelectRef = ref<destSelectType | null>(null);

const dateValue = ref("");

// 用户画像-健康比例 num为按人数，medical为按医疗支出
const userDataHealthRiskRatioType = ref("num");

const destOptions = [
  {
    label: "太原市",
    value: "140100"
  },
  {
    label: "芜湖市",
    value: "340200"
  },
  {
    label: "南京市",
    value: "320100"
  }
];

const trendLineRef = ref(null);
const userChartRef = ref(null);
const slowDiseaseXyRef1 = ref(null);
const slowDiseaseXyRef2 = ref(null);
const slowDiseaseXtRef1 = ref(null);
const slowDiseaseXtRef2 = ref(null);
const slowDiseaseXzRef1 = ref(null);
const slowDiseaseXzRef2 = ref(null);

const trendLineIns = ref(null);
const userChartIns = ref(null);
const slowDiseaseXyIns = ref(null);
const slowDiseaseXyIns2 = ref(null);
const slowDiseaseXtIns = ref(null);
const slowDiseaseXtIns2 = ref(null);
const slowDiseaseXzIns = ref(null);
const slowDiseaseXzIns2 = ref(null);

const trendLineDataOption = reactive({
  title: {
    text: "趋势分析(人)",
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true
  },

  xAxis: {
    type: "category",
    boundaryGap: false,
    data: lastWeeks
  },
  yAxis: {
    type: "value"
  },
  series: [
    {
      name: "新用户（人）",
      type: "line",
      stack: "Total",
      data: [120, 132, 101, 134, 90, 230, 210]
    }
  ]
});

function initTrendLine(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(trendLineDataOption as any);
  return getInstance();
}

const userChartOption = reactive({
  title: {
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  color: ["#00A870", "#F07600", "#FF0000"],
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b} : {c}%"
  },
  legend: {
    data: ["高风险", "中风险", "低风险"]
  },
  series: [
    {
      name: "健康风险比例",
      type: "funnel",
      left: "10%",
      top: 60,
      bottom: 60,
      width: "80%",
      min: 0,
      max: 100,
      minSize: "0%",
      maxSize: "100%",
      sort: "ascending",
      gap: 2,
      label: {
        show: true,
        position: "outer",
        formatter: "{b}\n{c}%"
      },
      labelLine: {
        length: 10,
        lineStyle: {
          width: 1,
          type: "solid"
        }
      },
      itemStyle: {
        borderColor: "#fff",
        borderWidth: 1
      },
      emphasis: {
        label: {
          fontSize: 20
        }
      },
      data: []
    }
  ]
});

function initUserChart(elRef): echartsTypes.ECharts {
  // console.log("initUserChart elRef:", elRef);
  // console.log("initUserChart data:", data);
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  // console.log("setOptions:", setOptions);
  setOptions(userChartOption as any);
  return getInstance();
}

const xyPieChart1DataOption = reactive({
  title: {
    text: "达标率（血压）",
    left: "center",
    show: false
  },

  tooltip: {
    show: true,
    trigger: "item"
  },

  legend: {
    orient: "vertical",
    left: "left",
    show: false
  },
  series: [
    {
      name: "血压",
      type: "pie",
      radius: "50%",
      data: [
        { value: 54, name: "54%" },
        { value: 46, name: "" }
      ],
      labelLine: {
        show: false
      },
      label: {
        show: true,
        position: "inside"
      }
    }
  ]
});

function initXyPieChart1(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(xyPieChart1DataOption as any);
  return getInstance();
}

async function setXyPieChart1DataOption() {
  const xYRateRes = (
    await getXyRate(destSelectRef.value.userSelectedRegions.cityId)
  )?.result[0];
  xyPieChart1DataOption.series[0].data = [
    {
      value: Math.floor(xYRateRes.value * 100),
      name: xYRateRes.value * 100 + "%"
    },
    { value: 100 - xYRateRes.value * 100, name: "" }
  ];
  slowDiseaseXyIns.value.setOption(xyPieChart1DataOption);
}

const xyPieChart2DataOption = reactive({
  title: {
    text: "达标率（血压）",
    left: "center",
    show: false
  },
  tooltip: {
    show: true,
    trigger: "item"
  },

  legend: {
    orient: "vertical",
    left: "left",
    show: false
  },
  series: [
    {
      name: "血压",
      type: "pie",
      radius: "50%",
      data: [
        { value: 70, name: "70%" },
        { value: 30, name: "" }
      ],
      labelLine: {
        show: false
      },
      label: {
        show: true,
        position: "inside"
      }
    }
  ]
});

function initXyPieChart2(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(xyPieChart2DataOption as any);
  return getInstance();
}

async function setXyPieChart2DataOption() {
  const xYRateRes = (
    await getXyRate(destSelectRef.value.userSelectedRegions.cityId)
  ).result[1];
  xyPieChart2DataOption.series[0].data = [
    {
      value: Math.floor(xYRateRes.value * 100),
      name: xYRateRes.value * 100 + "%"
    },
    { value: 100 - xYRateRes.value * 100, name: "" }
  ];
  slowDiseaseXyIns2.value.setOption(xyPieChart2DataOption);
}

const xtPieChart1DataOption = reactive({
  title: {
    text: "达标率（血糖）",
    left: "center",
    show: false
  },
  tooltip: {
    show: true,
    trigger: "item"
  },
  legend: {
    orient: "vertical",
    left: "left",
    show: false
  },
  series: [
    {
      name: "血糖",
      type: "pie",
      radius: "50%",
      data: [
        { value: 54, name: "54%" },
        { value: 46, name: "" }
      ],
      labelLine: {
        show: false
      },
      label: {
        show: true,
        position: "inside"
      }
    }
  ]
});

function initXtPieChart1(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(xtPieChart1DataOption as any);
  return getInstance();
}

async function setXtPieChart1DataOption() {
  const rateRes = (
    await getXtRate(destSelectRef.value.userSelectedRegions.cityId)
  )?.result[0];
  xtPieChart1DataOption.series[0].data = [
    { value: Math.floor(rateRes.value * 100), name: rateRes.value * 100 + "%" },
    { value: 100 - rateRes.value * 100, name: "" }
  ];
  slowDiseaseXtIns.value.setOption(xtPieChart1DataOption);
}

const xtPieChart2DataOption = reactive({
  title: {
    text: "达标率（血糖）",
    left: "center",
    show: false
  },
  tooltip: {
    show: true,
    trigger: "item"
  },
  legend: {
    orient: "vertical",
    left: "left",
    show: false
  },
  series: [
    {
      name: "血糖",
      type: "pie",
      radius: "50%",
      data: [
        { value: 70, name: "70%" },
        { value: 30, name: "30%" }
      ],
      labelLine: {
        show: false
      },
      label: {
        show: true,
        position: "inside"
      }
    }
  ]
});

function initXtPieChart2(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(xtPieChart2DataOption as any);
  return getInstance();
}

async function setXtPieChart2DataOption() {
  const rateRes = (
    await getXtRate(destSelectRef.value.userSelectedRegions.cityId)
  ).result[1];
  // console.log("setXtPieChart2DataOption rateRes:", rateRes);
  xtPieChart2DataOption.series[0].data = [
    {
      value: Math.floor(rateRes.value * 100),
      name: (rateRes.value * 100).toFixed(0) + "%"
    },
    { value: 100 - rateRes.value * 100, name: "" }
  ];
  slowDiseaseXtIns2.value.setOption(xtPieChart2DataOption);
}

const xzPieChart1DataOption = reactive({
  title: {
    text: "达标率（血脂）",
    left: "center",
    show: false
  },
  tooltip: {
    show: true,
    trigger: "item"
  },
  legend: {
    orient: "vertical",
    left: "left",
    show: false
  },
  series: [
    {
      name: "血脂",
      type: "pie",
      radius: "50%",
      data: [
        { value: 54, name: "54%" },
        { value: 46, name: "46%" }
      ],
      labelLine: {
        show: false
      },
      label: {
        show: true,
        position: "inside"
      }
    }
  ]
});

function initXzPieChart1(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(xzPieChart1DataOption as any);
  return getInstance();
}

async function setXzPieChart1DataOption() {
  const rateRes = (
    await getXzRate(destSelectRef.value.userSelectedRegions.cityId)
  )?.result[0];
  xzPieChart1DataOption.series[0].data = [
    { value: Math.floor(rateRes.value * 100), name: rateRes.value * 100 + "%" },
    { value: 100 - rateRes.value * 100, name: "" }
  ];
  slowDiseaseXzIns.value.setOption(xzPieChart1DataOption);
}
const xzPieChart2DataOption = reactive({
  title: {
    text: "达标率（血脂）",
    left: "center",
    show: false
  },
  tooltip: {
    show: true,
    trigger: "item"
  },
  legend: {
    orient: "vertical",
    left: "left",
    show: false
  },

  series: [
    {
      name: "血脂",
      type: "pie",
      radius: "50%",
      data: [
        { value: 70, name: "70%" },
        { value: 30, name: "30%" }
      ],
      labelLine: {
        show: false
      },
      label: {
        show: true,
        position: "inside"
      }
    }
  ]
});
function initXzPieChart2(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(xzPieChart2DataOption as any);
  return getInstance();
}

async function setXzPieChart2DataOption() {
  const rateRes = (
    await getXzRate(destSelectRef.value.userSelectedRegions.cityId)
  ).result[1];
  xzPieChart2DataOption.series[0].data = [
    { value: Math.floor(rateRes.value * 100), name: rateRes.value * 100 + "%" },
    { value: 100 - rateRes.value * 100, name: "" }
  ];
  slowDiseaseXzIns2.value.setOption(xzPieChart2DataOption);
}

function resizeChart() {
  // console.log("resizeChart");
  trendLineIns.value?.resize();
  userChartIns.value?.resize();
  slowDiseaseXyIns.value?.resize();
  slowDiseaseXyIns2.value?.resize();
  slowDiseaseXtIns.value?.resize();
  slowDiseaseXtIns2.value?.resize();
  slowDiseaseXzIns.value?.resize();
  slowDiseaseXzIns2.value?.resize();
}

// 首页概览数据
const indexValue = ref({});

// 用户画像-健康风险比例
const userHospitalRiskData = ref<RiskDataType>({
  data: [],
  xaxis: []
});

async function clickGetHealthIndexHospitalRiskData() {
  let dataType = userDataHealthRiskRatioType.value;
  dataType = dataType === "num" ? "medical" : "num";
  userDataHealthRiskRatioType.value = dataType;

  setUserChartOptionData();
}

async function setUserChartOptionData() {
  const dataType = userDataHealthRiskRatioType.value;
  if (dataType === "num") {
    userHospitalRiskData.value = (
      await getHealthIndexHospitalRiskByNum(
        destSelectRef.value.userSelectedRegions.cityId
      )
    )?.result;
  } else {
    userHospitalRiskData.value = (
      await getHealthIndexHospitalRiskByMedical(
        destSelectRef.value.userSelectedRegions.cityId
      )
    )?.result;
  }

  userChartOption.series[0].data = userHospitalRiskData.value.data.map(
    (item, index) => {
      return {
        value: item * 100,
        name: userHospitalRiskData.value.xaxis[index]
      };
    }
  );
  userChartIns.value.setOption(userChartOption);
}

// 用户画像，会员疾病占比 num为按人数，medical为按医疗支出
const userDataDiseaseRatioType = ref("num");
const userDataDiseaseRatioData = ref([]);

function changeDiseaseRatioType() {
  let dataType = userDataDiseaseRatioType.value;
  dataType = dataType === "num" ? "medical" : "num";
  userDataDiseaseRatioType.value = dataType;
  setDiseaseRatioData();
}

async function setDiseaseRatioData() {
  if (userDataDiseaseRatioType.value === "num") {
    const res = (
      await getHealthIndexMemberRatioByNum(
        destSelectRef.value.userSelectedRegions.cityId
      )
    )?.result || {
      data: [],
      xaxis: []
    };
    let maxNum = 0;
    res.data.forEach(item => {
      if (item > maxNum) {
        maxNum = item;
      }
    });
    userDataDiseaseRatioData.value = res.data
      .map((item, index) => {
        return {
          name: res.xaxis[index],
          value: (item * 100).toFixed(0),
          width: (item / maxNum) * 200,
          index: index + 1
        };
      })
      .slice(0, 5);
  } else {
    const res = (
      await getHealthIndexMemberRatioByMedical(
        destSelectRef.value.userSelectedRegions.cityId
      )
    )?.result || {
      data: [],
      xaxis: []
    };
    let maxNum = 0;
    res.data.forEach(item => {
      if (item > maxNum) {
        maxNum = item;
      }
    });
    userDataDiseaseRatioData.value = res.data
      .map((item, index) => {
        return {
          name: res.xaxis[index],
          value: (item * 100).toFixed(0),
          width: (item / maxNum) * 200,
          index: index + 1
        };
      })
      .slice(0, 5);
  }
}

// 慢病管理效果

const reHospitalRatioType = ref("num");
const reHospitalRatioData = ref([]);

function changeReHospitalType() {
  let dataType = reHospitalRatioType.value;
  dataType = dataType === "num" ? "medical" : "num";
  reHospitalRatioType.value = dataType;
  setReHospitalRatioData();
}

async function setReHospitalRatioData() {
  if (reHospitalRatioType.value === "num") {
    const res = (
      await getReHospitalDataByNum(
        destSelectRef.value.userSelectedRegions.cityId
      )
    )?.result || {
      data: [],
      xaxis: []
    };

    // console.log("res.data:", res.data);
    const totalNum = res.data.reduce((total, cur) => {
      return total + cur;
    }, 0);

    reHospitalRatioData.value = res.data.map((item, index) => {
      return {
        name: res.xaxis[index],
        value: formatNum(item),
        width: (item / totalNum) * 200,
        index: index + 1
      };
    });
    reHospitalRatioData.value.unshift({
      name: "总人次",
      value: formatNum(totalNum),
      width: (totalNum / totalNum) * 200,
      index: 0
    });
  } else {
    const res = (
      await getReHospitalDataByMedical(
        destSelectRef.value.userSelectedRegions.cityId
      )
    )?.result || {
      data: [],
      xaxis: []
    };
    const totalNum = res.data.reduce((total, cur) => {
      return total + cur;
    }, 0);
    reHospitalRatioData.value = res.data.map((item, index) => {
      return {
        name: res.xaxis[index],
        value: formatNum(item),
        width: (item / totalNum) * 200,
        index: index + 1
      };
    });

    reHospitalRatioData.value.unshift({
      name: "总费用",
      value: formatNum(totalNum),
      width: (totalNum / totalNum) * 200,
      index: 0
    });
  }
}

// 重疾管理效果

const seriousIllnessType = ref("num");
const seriousIllnessData = ref([]);

function changeSeriousIllnessType() {
  let dataType = seriousIllnessType.value;
  dataType = dataType === "num" ? "medical" : "num";
  seriousIllnessType.value = dataType;
  setSeriousIllnessData();
}

async function setSeriousIllnessData() {
  if (seriousIllnessType.value === "num") {
    const res = (
      await getSeriousIllnessDataByNum(
        destSelectRef.value.userSelectedRegions.cityId
      )
    )?.result || {
      data: [],
      xaxis: []
    };

    // console.log("res.data:", res.data);
    // const totalNum = res.data.reduce((total, cur) => {
    //   return total + cur;
    // }, 0);

    let maxNum = 0;
    res.data.forEach(item => {
      if (item > maxNum) {
        maxNum = item;
      }
    });

    seriousIllnessData.value = res.data.map((item, index) => {
      return {
        name: res.xaxis[index],
        value: formatNum(item),
        width: (item / maxNum) * 200,
        index: index + 1
      };
    });
  } else {
    const res = (
      await getSeriousIllnessDataByMedical(
        destSelectRef.value.userSelectedRegions.cityId
      )
    )?.result || {
      data: [],
      xaxis: []
    };
    let maxNum = 0;
    res.data.forEach(item => {
      if (item > maxNum) {
        maxNum = item;
      }
    });
    seriousIllnessData.value = res.data.map((item, index) => {
      return {
        name: res.xaxis[index],
        value: formatNum(item),
        width: (item / maxNum) * 200,
        index: index + 1
      };
    });
  }
}

function destChange(cityObj) {
  // console.log("destChange2:", cityObj);
  globalDataStoreHook().CHANGE_CITY_ID(cityObj.cityId);
  init(cityObj.cityId);
  initEchart();
}

// 居民会员总数

const memberTotalNum = ref<number>(0);
// 慢病改善
const chronicDiseaseBetterNum = ref(0);

// 用药改善
const useDrugBetterNum = ref(0);

const memOkNum = ref(0);

function resetData() {
  memberTotalNum.value = 0;
  chronicDiseaseBetterNum.value = 0;
  useDrugBetterNum.value = 0;
  memOkNum.value = 0;
}

async function init(cityId) {
  resetData();

  // 初始化echart必须在 await之前，否则会报错
  indexValue.value = (await getHealthIndexOverview(cityId))?.result;
  // 获取管理居民总数
  const memberTotalRes = (await getMemberNum(cityId))?.result;
  // console.log('memberTotalRes:',memberTotalRes)
  memberTotalNum.value = memberTotalRes.value;

  const chronicDiseaseBetterNumRes = (await getChronicDiseaseBetterNum(cityId))
    ?.result;
  chronicDiseaseBetterNum.value = chronicDiseaseBetterNumRes.value;

  useDrugBetterNum.value = (await getUseDrugBetterNum(cityId))?.result.value;

  memOkNum.value = (await getMemOkNum(cityId))?.result?.value;
}

function initEchart() {
  setDiseaseRatioData();

  setReHospitalRatioData();

  setSeriousIllnessData();
  setUserChartOptionData();
  // 血压达标率
  setXyPieChart1DataOption();
  setXyPieChart2DataOption();
  // 血糖
  setXtPieChart1DataOption();
  setXtPieChart2DataOption();
  // 血脂
  setXzPieChart1DataOption();
  setXzPieChart2DataOption();
}

onMounted(() => {
  // console.log(
  //   "destSelectRef.value.userSelectedRegions.cityId:",
  //   destSelectRef.value.userSelectedRegions.cityId ||
  //     destSelectRef.value.userSelectedRegions.provinceId
  // );
  console.log(
    "destSelectRef.value.userSelectedRegions.cityId:",
    destSelectRef.value.userSelectedRegions
  );
  init(
    destSelectRef.value.userSelectedRegions.cityId ||
      destSelectRef.value.userSelectedRegions.provinceId
  );
  // 城市id

  userChartIns.value = initUserChart(userChartRef);
  trendLineIns.value = initTrendLine(trendLineRef);

  slowDiseaseXyIns.value = initXyPieChart1(slowDiseaseXyRef1);
  slowDiseaseXyIns2.value = initXyPieChart2(slowDiseaseXyRef2);

  slowDiseaseXtIns.value = initXtPieChart1(slowDiseaseXtRef1);
  slowDiseaseXtIns2.value = initXtPieChart2(slowDiseaseXtRef2);

  slowDiseaseXzIns.value = initXzPieChart1(slowDiseaseXzRef1);
  slowDiseaseXzIns2.value = initXzPieChart2(slowDiseaseXzRef2);

  initEchart();

  window.addEventListener("resize", resizeChart);
});
onUnmounted(() => {
  window.removeEventListener("resize", resizeChart);
});
</script>
<style scoped lang="scss">
.search {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .el-select {
    margin-right: 20px;
  }

  .el-date-picker {
    margin-left: 20px;
  }
}

.p-cont {
  background-color: white;
  border-radius: 4px;

  .drug {
    .title {
      span {
        font-size: 24px;
      }
    }

    .user-panel {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20px;

      .up-item {
        border: 1px solid #eee;
        border-radius: 8px;
        width: 24%;
        padding: 20px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
        height: 130px;

        .up-des {
          @include panelSubTitle;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }

        .up-num {
          @include panelBigTitle;
          margin-top: 10px;
        }

        .up-inc {
          @include panelThirdTitle;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 10px;

          .up-inc-left {
            display: flex;
            align-items: center;
            width: 110px;
            justify-content: space-between;

            .green {
              color: #00a870;
            }

            .red {
              color: #e54d59;
            }
          }

          .up-inc-right {
            cursor: pointer;
          }
        }
      }
    }
  }

  .trend {
    margin-top: 30px;

    .trend-content {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .tc-single {
        width: 100%;
      }

      .tc-left {
        width: 70%;
      }

      .tc-btn {
        text-align: left;
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
      }

      .tc-line {
        width: 100%;
        height: 400px;
        margin-top: 20px;
      }

      .tc-right {
        width: calc(30% - 20px);
        box-sizing: border-box;
        padding-top: 55px;
        border-left: 1px solid #eee;
        margin-top: 20px;
        margin-left: 40px;
        padding-left: 40px;

        .tc-r-item {
          width: 100%;
          height: 200px;
          box-sizing: border-box;
          padding-left: 20px;

          .tc-r-title {
            @include panelSubTitle;
          }

          .tc-r-num {
            @include panelBigTitle;
            margin-top: 20px;
          }

          .tc-r-inc {
            @include panelThirdTitle;
            display: flex;
            align-items: center;
            margin-top: 20px;
          }
        }
      }
    }
  }
}

.section {
  .title {
    span {
      font-size: 24px;
    }
  }

  .user-panel {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;

    .up-item {
      border: 1px solid #eee;
      border-radius: 8px;
      width: 24%;
      padding: 20px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      height: 130px;

      &.hidden {
        visibility: hidden;
      }

      .up-des {
        @include panelSubTitle;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .up-num {
        @include panelBigTitle;
        margin-top: 10px;
      }

      .up-inc {
        @include panelThirdTitle;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 10px;

        .up-inc-left {
          display: flex;
          align-items: center;
          width: 110px;
          justify-content: space-between;
          color: #bbb;

          .green {
            color: #00a870;
          }

          .red {
            color: #e54d59;
          }
        }

        .up-inc-right {
          cursor: pointer;
          color: #bbb;
        }
      }
    }
  }

  .chart {
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .chart-item {
      width: calc(50% - 20px);

      .ch-btns {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height: 60px;
        margin-bottom: 20px;
        width: 100%;

        .chart-title {
          flex: auto;
          font-size: 18px;
          display: flex;
          align-items: center;
        }
      }

      &.chart-flex-col {
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: space-between;

        .ch-row {
          display: flex;
          align-items: center;
          justify-content: space-evenly;
          height: 100px;
          width: 100%;
          margin-bottom: 20px;

          .ch-col-label {
            width: 80px;
            text-align: center;
            font-size: 16px;
          }

          .ch-col-pie {
            width: 180px;
            height: 180px;
          }
        }

        .ch-list {
          width: 100%;
        }
      }

      .ch-chart {
        height: 300px;
      }

      .ch-list {
        height: 300px;

        .ch-t-index {
          width: 24px;
          height: 24px;
          border-radius: 20px;
          display: inline-block;
          background: #0052d9;
          color: white;
          text-align: center;
          line-height: 24px;
        }

        .ch-t-cont {
          display: flex;
          align-items: center;
          word-break: keep-all;

          .ch-t-bar {
            height: 12px;
            border-radius: 20px;
            background: #eee;

            .ch-t-bar-inner {
              height: inherit;
              background: #0052d9;
              border-radius: 20px;
            }
          }

          .ch-t-num {
            margin-left: 5px;
          }
        }
      }
    }
  }
}

.part2 {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;

  .section {
    width: calc(50% - 20px);

    .user-panel {
      .up-item {
        width: 49%;
      }
    }

    .chart {
      // margin-left: 40px;
      .chart-item {
        width: 100%;
      }
    }
  }
}
</style>
